<?php
namespace App\Api;

use PhalApi\Api;
use App\Domain\Order as Domain_Order;
use App\Domain\Charge as Domain_Charge;
use App\Api\Payment as Payment;
use App\Api\Result as Result;
/**
 * 音乐
 */

class Order extends Api {

	public function getRules() {
        return array(
            'getOrderConfig' => array(
                'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
				'token' => array('name' => 'token', 'type' => 'string',  'desc' => '用户token'),
			),
            'createOrder' => array(
                'uid' => array('name' => 'uid', 'type' => 'int', 'desc' => '用户ID'),
                'token' => array('name' => 'token', 'type' => 'string',  'desc' => '用户token'),
                'rule_id' => array('name' => 'rule_id', 'type' => 'int', 'desc' => '商品id'),
                'paytype' => array('name' => 'paytype', 'type' => 'int', 'desc' => '支付方式'),
                'channel' => array('name' => 'channel', 'type' => 'int', 'desc' => '支付通道'),
                'source' => array('name' => 'source', 'type' => 'int', 'default'=>'0', 'desc' => '来源设备,0web，1android，2ios，3小程序'),
			),
			'xfyun' => array(
                'text' => array('name' => 'text', 'type' => 'string', 'desc' => '文本'),
                'from' => array('name' => 'from', 'type' => 'string', 'desc' => '翻译的语言'),
                'to' => array('name' => 'to', 'type' => 'string', 'desc' => '翻译成的语言')
			),
            'notify' => array(
            ),
           
        );
	}
	
	public $baseUrl = "https://api.maxpay1688.com/api/pay/add";
	public $merchant = "1932730100690763777";
	public $secret = "c2060886-e567-458e-90c6-71182393f2ad";
	
    public function notify(){
        $data = $_POST;
        if($data['status'] == 1){
            $result = new Result();
            $result->charge($data['outtradeno']);
        }
    }
	public function getOrderConfig() {
        $rs = array('code' => 0, 'msg' => '', 'info' => array());
        $uid=\App\checkNull($this->uid);
        $token=\App\checkNull($this->token);
        
		$checkToken=\App\checkToken($uid,$token);
		
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
		$userInfo = \App\getUserInfo($uid);
		if(empty($userInfo['country'])){
		    $rs['code'] = 1001;
			$rs['msg'] = \PhalApi\T('请选择国家！');
			return $rs;
		}
		$country_id = $userInfo['country']['id'];
		
		$list = \PhalApi\DI()->notorm->methods
				->select('*')
				->order('id asc')
				->fetchAll();
		//print_r($list);exit;
		
		$returnlist = [];
		if(!empty($list)){
		    foreach ($list as $k=>$v){
		        $v['img_url'] = \App\get_upload_path($v['img_url']);
		        if(empty($v['channel_id'])){
		            unset($list[$k]);
		        }else{
		            $channel = \PhalApi\DI()->notorm->channel
                				->select('*')
                				->where("find_in_set(id,'".$v['channel_id']."')")
                				->where("find_in_set('".$country_id."',countrys)")
                				->fetchAll();
                    if(empty($channel)){
                        unset($list[$k]);
                    }else{
                        foreach ($channel as &$v1){
        			        $v1['img_url'] = \App\get_upload_path($v1['img_url']);
        			    }
                        $v['channel'] = $channel;
                        $returnlist[] = $v;
                    }
                    
                    
		        }
		    }
		}
        /*$list = \PhalApi\DI()->notorm->channel
				->select('*')
				->fetchAll();
		
		if(!empty($list)){
		   foreach ($list as $k=>$v){
		        $countrys = explode(',',$v['countrys']);
		        if(!in_array($country_id,$countrys)){
		            unset($list[$k]);
		        }else{
		            $list[$k]['img_url'] = \App\get_upload_path($v['img_url']);
        		    $methods = \PhalApi\DI()->notorm->methods
        				->select('*')
        				->where('channel_id',$v['id'])
        				->fetchAll();
        			if(!empty($methods)){
        			    foreach ($methods as &$v1){
        			        $v1['img_url'] = \App\get_upload_path($v1['img_url']);
        			    }
        			}
        			$list[$k]['methods'] = $methods;
		        }
    		} 
		}*/
        
        $rs['info'] = $returnlist;
        return $rs;
	}
	
	/*public function createOrder(){
	    $rs = array('code' => 0, 'msg' => '', 'info' => array());
	    
	    $uid=\App\checkNull($this->uid);
	    $amount=\App\checkNull($this->amount);
	    $paytype=\App\checkNull($this->paytype);
	    $channel=\App\checkNull($this->channel);
	    
	    $params = [
	        'amount' => $amount,
	        'merchant' => $this->merchant,
	        'paytype' => $paytype,
	        'outtradeno' => $this->order_no(),
	        'notifyurl' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Order.notify',
	        'returndataformat' => 'serverhtml',
	    ];
	    
	    $sign = $this->sign($params);
	    $params['sign'] = $sign;
	    
	    $result = $this->curl_post($this->baseUrl, $params);
	    $rs['info'] =  $result ;
	    return $rs;
	}*/
	
		
	public function maxpay($amount,$orderid,$paytype){
	    $params = [
	        'amount' => $amount,
	        'merchant' => $this->merchant,
	        'paytype' => $paytype,
	        'outtradeno' => $orderid,
	        'notifyurl' => $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/phalapi/?service=Order.notify',
	        'returndataformat' => 'serverhtml',
	    ];
	    $sign = $this->sign($params);
	    $params['sign'] = $sign;
	    $result = $this->curl_post($this->baseUrl, $params);
	    $rs['info'] =  $result ;
	    return $rs;
	}
	/* 获取订单号 */
	protected function getOrderid($uid){
		$orderid=$uid.'_'.date('YmdHis').rand(100,999);
		return $orderid;
	}
	public function createOrder(){
	    $rs = array('code' => 0, 'msg' => '', 'info' => array());
	    $token=\App\checkNull($this->token);
	    $uid=\App\checkNull($this->uid);
	    $changeid=\App\checkNull($this->rule_id);
	    $paytype=\App\checkNull($this->paytype);
	    $channel=\App\checkNull($this->channel);
	    $source = \App\checkNull($this->source);
	    $checkToken=\App\checkToken($uid,$token);
		
		if($checkToken==700){
			$rs['code'] = $checkToken;
			$rs['msg'] = \PhalApi\T('您的登陆状态失效，请重新登陆！');
			return $rs;
		}
		
		$user = \App\getUserInfo($uid);
		$country = $user['country'];
		$currency = $country['unit'];
		$rule = \PhalApi\DI()->notorm->charge_rules
					->select('*')
					->where('id',$changeid)
					->fetchOne();
		
		if(!empty($rule['money'])){
		    $money = json_decode($rule['money'],true);
		    $amount = '';
            foreach ($money as $k1=>$v1){
                if($country['code'] == $k1){
                    $amount = $v1;
                }else{
                    if($k1 == 'USD'){
                        $amount = $v1;
                        $currency = 'USD';
                    }
                }
            }
            if(empty($amount)){
                $rs['code'] = 1001;
    			$rs['msg'] = \PhalApi\T('暂不支持充值！');
    			return $rs;
            }
		}else{
		    $rs['code'] = 1002;
			$rs['msg'] = \PhalApi\T('暂不支持充值！');
			return $rs;
		}
		$orderid=$this->getOrderid($uid);
        $orderid=$orderid."_0";
	    $orderinfo=array(
			"uid"=>$uid,
			"touid"=>$uid,
			"money"=>$amount,
			"coin"=>$rule['coin'],
			"orderno"=>$orderid,
			"type"=>$paytype,
			"status"=>0,
			"addtime"=>time()
		);
		$domain = new Domain_Charge();
		$info = $domain->setOrder($changeid,$orderinfo);
		if(!$info){
			$rs['code']=1001;
			$rs['msg']='订单生成失败';
            return $rs;	
		}
		$channel_info = \PhalApi\DI()->notorm->channel
			->select('*')
			->where('id',$channel)
			->fetchOne();
		
		if(empty($channel_info)){
		    $rs['code']=1003;
			$rs['msg']='暂不支持充值';
            return $rs;
		}
		$method_info = \PhalApi\DI()->notorm->methods
			->select('*')
			->where('id',$paytype)
			->fetchOne();
		if(empty($method_info)){
		    $rs['code']=1004;
			$rs['msg']='暂不支持充值';
            return $rs;
		}
		if($method_info['paytype'] == 'redirect_pay'){
		    $payment = new Payment();
		    $result = $payment->redirect_pay($amount,$orderid,$currency,$source);
		    return $result;
		}elseif($method_info['paytype'] == 1 || $method_info['paytype'] == 2 || $method_info['paytype'] == 3){
		    $result = $this->maxpay($amount,$orderid,$method_info['paytype']);
		    return $result;
		}elseif($method_info['paytype'] == 'Paypal'){
		    $payment = new Payment();
		    $result = $payment->succpay($amount,$orderid,$method_info['paytype'],$currency);
		    return $result;
		}
	}
	
	public function curl_post($url, $data){
	    $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        // 默认Header配置
        $defaultHeaders = [
            'Content-Type: application/json',
        ];
        // $finalHeaders = array_merge($defaultHeaders, $headers);
        
        curl_setopt($ch, CURLOPT_HTTPHEADER, $defaultHeaders);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        
        // 安全配置
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $response = curl_exec($ch);
        if(curl_errno($ch)) {
            throw new Exception(curl_error($ch));
        }
        curl_close($ch);
        return json_decode($response, true);
	}
	
	public function order_no(){
	    return 'NO.'.date('YmdHis').rand(1000,9999);
	}
	
	public function sign($params){
	    ksort($params);
	    $paramString = strtolower(http_build_query($params))."&secret=".$this->secret;
        $sign = md5($paramString);
        return $sign;
	}
	
	public function xfyun() {
	    $text=\App\checkNull($this->text);
	    $from=\App\checkNull($this->from);
	    $to=\App\checkNull($this->to);
	    if(strstr($text,'[')){
	        $result['code'] = 0;
            $result['info']['from'] = $from;
            $result['info']['to'] = $to;
            $result['info']['trans_result']['dst'] = $text;
            $result['info']['trans_result']['src'] = $text;
            return $result;
	    }
		//在控制台-我的应用-机器翻译获取
        $app_id = "8a5057ba";
		//在控制台-我的应用-机器翻译获取
        $api_sec = "MWY5NzQ2N2VhZjdiNDQ5OTE4OTQxMmMx";
		//在控制台-我的应用-机器翻译获取
        $api_key = "ebd2e751ab73381b28a088ff1247174e";
		// 机器翻译接口地址
        $url = "https://ntrans.xfyun.cn/v2/ots";

        //body组装
        // $text = "中华人民共和国于1949年成立";//待翻译文本
        $body = json_encode($this->getBody($app_id, $from, $to, $text));

        // 组装http请求头
        $date =gmdate('D, d M Y H:i:s') . ' GMT';

        $digestBase64  = "SHA-256=".base64_encode(hash("sha256", $body, true));
        $builder = sprintf("host: %s
date: %s
POST /v2/ots HTTP/1.1
digest: %s", "ntrans.xfyun.cn", $date, $digestBase64);
        // echo($builder);
        $sha = base64_encode(hash_hmac("sha256", $builder, $api_sec, true));

        $authorization = sprintf("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", $api_key,"hmac-sha256",
            "host date request-line digest", $sha);

        $header = [
            "Authorization: ".$authorization,
            'Content-Type: application/json',
            'Accept: application/json,version=1.0',
            'Host: ntrans.xfyun.cn',
            'Date: ' .$date,
            'Digest: '.$digestBase64
        ];
        $response = $this->tocurl($url, $header, $body);
        $body = json_decode($response['body'],true);
        if($body['code'] ==0){
            $result['code'] = $body['code'];
            $result['info'] = $body['data']['result'];
            return $result;
            return json_decode($response['body'], true);
        }else{
            $rs['code']=1003;
			$rs['msg']='err';
            return $rs;
        }
        //return $response;
    }
	
	public function tocurl($url, $header, $content){
        $ch = curl_init();
        if(substr($url,0,5)=='https'){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
            curl_setopt($ch, CURLOPT_SSLVERSION, 1);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        if (is_array($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_POST, true);
        if (!empty($content)) {
            if (is_array($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($content));
            } else if (is_string($content)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
            }
        }
        $response = curl_exec($ch);
        $error=curl_error($ch);
        //var_dump($error);
        if($error){
            die($error);
        }
        $header = curl_getinfo($ch);

        curl_close($ch);
        $data = array('header' => $header,'body' => $response);
        return $data;
    }
    

    public function getBody($app_id, $from, $to, $text) {
        $common_param = [
            'app_id'   => $app_id
        ];

        $business = [
            'from' => $from,
            'to'   => $to,
        ];

        $data = [
            "text" => base64_encode($text)
        ];

        return $body = [
            'common' => $common_param,
            'business' => $business,
            'data' => $data
        ];
    }

}
